package com.gosling.gosling;


import com.gosling.cloudspace.tools.IOTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.maven.model.Build;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.apache.maven.model.io.xpp3.MavenXpp3Writer;
import org.codehaus.plexus.util.xml.Xpp3Dom;

import java.io.*;
import java.util.List;


/**
 * 输入任何一个pom文件，会修改pom文件，插入以下代码
 * <plugin>
 * <groupId>org.owasp</groupId>
 * <artifactId>dependency-check-maven</artifactId>
 * <version>7.1.1</version>
 * <configuration>
 * <formats>HTML,JSON</formats>
 * <assemblyAnalyzerEnabled>false</assemblyAnalyzerEnabled>
 * </configuration>
 * </plugin>
 * <p>
 * Maven依赖地址
 * <dependency>
 * <groupId>org.apache.maven</groupId>
 * <artifactId>maven-model</artifactId>
 * <version>3.6.0</version>
 * </dependency>
 *
 * @author ZhangRenJie
 */
@Slf4j
public class SysOdcPomModifierTest {

    public static void main(String[] args) {
        SysOdcPomModifierTest replaceFileContent = new SysOdcPomModifierTest();
        try {
            replaceFileContent.insertOdcMavenBuildPlugin(new File("E:\\Rj\\codex-server\\main\\src\\main\\java\\pom.xml"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void insertOdcMavenBuildPlugin(File pomXml) throws Exception {
        FileInputStream fis = null;
        FileWriter writer = null;
        try {
            Plugin plugin = new Plugin();
            Xpp3Dom javadocConfig = new Xpp3Dom("configuration");
            Xpp3Dom formats = new Xpp3Dom("formats");
            Xpp3Dom assemblyAnalyzerEnabled = new Xpp3Dom("assemblyAnalyzerEnabled");
            plugin.setArtifactId("org.owasp");
            plugin.setArtifactId("dependency-check-maven");
            plugin.setVersion("7.1.1");
            formats.setValue("HTML,JSON");
            assemblyAnalyzerEnabled.setValue("false");
            javadocConfig.addChild(formats);
            javadocConfig.addChild(assemblyAnalyzerEnabled);
            plugin.setConfiguration(javadocConfig);
            fis = new FileInputStream((pomXml));
            MavenXpp3Reader reader = new MavenXpp3Reader();
            Model model = reader.read(fis);
            Build build = model.getBuild();
            List<Plugin> pluginList = build.getPlugins();
            //如果pom文件存在该依赖就不再重复添加！
            if (!pluginList.contains(plugin)) {
                pluginList.add(plugin);
            }
            writer = new FileWriter(pomXml);
            MavenXpp3Writer mavenXpp3Writer = new MavenXpp3Writer();
            mavenXpp3Writer.write(writer, model);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOTool.closeQuietly(writer);
            IOTool.closeQuietly(fis);
        }

    }
}


